package dpss.replicamanager;

import java.io.IOException;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Properties;

import dpss.commons.CustomLogger;
import dpss.commons.ServerNode;
import dpss.commons.UDPMessage;
import dpss.commons.UserInput;
import dpss.commons.Util;
import dpss.replicamanager.data.ServerNodes;
import dpss.replicamanager.gui.GUI;

/**
 * The replication manager that controls all replication nodes
 * 
 * @author musab.mirza
 *
 */ 
public class ReplicaManager {
	
	private static CustomLogger logger = CustomLogger.getInstance();
	
	
	/**
	 * Socket for UDP communication
	 */
	private DatagramSocket socket;
	
	/**
	 * The set of all registered nodes
	 */
	private ServerNodes nodes;
	
	/**
	 * Properties file
	 */
	private Properties prop;
	
	/**
	 * GUI
	 */
	private GUI gui;
	
	
	
	/**
	 * Main method to start the replica manager
	 */
	public static void main(String args[]){
		Util.printProgramName("REPLICA MANAGER");
		logger.logConsole(true);
		new ReplicaManager();
	}
	
	
	
	/**
	 * Constructor to initialize replica manager
	 * @throws SocketException
	 */
	private ReplicaManager(){
		
	
		// init the instance variables
		try {
			prop = Util.loadProperties("project.properties");
			nodes = new ServerNodes();
			socket = new DatagramSocket(Integer.parseInt( (String) prop.get("self.port")));
		} catch (NumberFormatException | SocketException e) {
			e.printStackTrace();
			System.exit(0);
		}
	
		// Start the complete gui with the data
		gui = new GUI(nodes);
		
		// Start the popup menu selection listening controller
		PopupClickController popupClickController = new PopupClickController(socket, nodes, gui);
		
		// Start the UDP listener controller
		new UDPListener(socket, nodes, gui).start();

	}

}